package cc.ls51.modules.SysUser.service.impl;

import cc.ls51.common.Constant;
import cc.ls51.common.PageUtils;
import cc.ls51.common.Query;
import cc.ls51.commons.dynamic.datasource.annotation.DataSource;
import cc.ls51.constant.DynamicDSFlag;
import cc.ls51.exception.BusinessException;
import cc.ls51.form.UserListForm;
import cc.ls51.form.UserLoginForm;
import cc.ls51.modules.SysUser.entity.SysUser;
import cc.ls51.modules.SysUser.mapper.SysUserMapper;
import cc.ls51.modules.SysUser.service.ISysUserService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author llf
 * @since 2019-08-27
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    @Autowired
    SysUserMapper sysUserMapper;

    @Override
    public SysUser getUserByUsername(UserLoginForm form) throws BusinessException {
        SysUser user = new SysUser();
        user.setUsername(form.getUsername());
        SysUser sysUser = sysUserMapper.selectOne(Wrappers.query(user));
        if(ObjectUtils.isEmpty(sysUser)){
            throw  new BusinessException("用户名不正确");
        }
        if(sysUser.getStatus()== Constant.UserState.STATE_LOCK.getValue()){
            throw  new BusinessException("账号已被锁定");
        }
        return sysUser;
    }

    @Override
    public PageUtils<SysUser> getPage(UserListForm params) {
        SysUser user = new SysUser();
        if(StringUtils.isNotEmpty(params.getUsername())){
            user.setUsername(params.getUsername());
        }
        IPage<SysUser> page = sysUserMapper.selectPage(
                new Query<SysUser>().getPage(params.getPageNumber(),params.getPageSize()),
                Wrappers.query(user)
        );

        return new PageUtils<>(page);
    }


    @DataSource(value = DynamicDSFlag.slave1)
    @Override
    public SysUser selectById2(Long id) {
        return sysUserMapper.selectById(id);
    }

    @Override
    public SysUser selectById(Long id) {
        return sysUserMapper.selectById(id);
    }
}
